package sk.vasicek.drinkagent.activity;

import sk.vasicek.drinkagent.R;
import sk.vasicek.drinkagent.domain.CustomDrink;
import sk.vasicek.drinkagent.service.BackgroundAdapter;
import sk.vasicek.drinkagent.service.CustomDrinkHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class CustomDrinkDetailActivity extends Activity {
	private static String TAG = "DrinkMapDetailActivity";

	private String nameString;
	private String noteString;

	private TextView name;
	private TextView note;

	private CustomDrinkHelper drinkDatabaseHelper;

	private Integer id;
	private CustomDrink customDrink;
	private TextView drinkPrice;
	private SeekBar drinkVolume;
	private SeekBar drinkConcentration;

	private Button updateButton;

	private Button removeButton;
	protected ImageButton settingsButton;
	protected ImageButton mapButton;
	protected ImageButton placesButton;
	protected ImageButton drinksButton;
	private TextView concentrationValue;
	private TextView volumeValue;

	SharedPreferences prefs;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.custom_detail);
		Log.d(TAG, "Started DrinkMapDetailActivity");

		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		BackgroundAdapter.updateBackgroundFromPrefs(prefs, this);

		drinkDatabaseHelper = new CustomDrinkHelper(this);

		nameString = getIntent().getExtras().getString(CustomDrink.DRINK_NAME);
		noteString = getIntent().getExtras().getString(CustomDrink.DRINK_NOTE);
		id = getIntent().getExtras().getInt(CustomDrink.DRINK_ID, 0);

		this.name = (TextView) this.findViewById(R.id.title);
		this.note = (TextView) this.findViewById(R.id.snippet);
		this.concentrationValue = (TextView) this.findViewById(R.id.concentrationValue);
		this.volumeValue = (TextView) this.findViewById(R.id.volumeValue);
		this.drinkPrice = (TextView) this.findViewById(R.id.price);
		this.drinkConcentration = (SeekBar) this.findViewById(R.id.concentrationSeek);
		this.drinkVolume = (SeekBar) this.findViewById(R.id.volumeSeek);
		drinkConcentration.setKeyProgressIncrement(1);
		drinkConcentration.setMax(1000);
		drinkVolume.setKeyProgressIncrement(1);
		drinkVolume.setMax(100);
		this.updateButton = (Button) this.findViewById(R.id.updateButton);
		this.removeButton = (Button) this.findViewById(R.id.removeButton);

		this.name.setText(nameString);
		this.note.setText(noteString);

		customDrink = drinkDatabaseHelper.getCustomDrinkByID(id);
		if (customDrink != null) {
			this.name.setText("" + customDrink.getName());
			this.note.setText("" + customDrink.getNote());
			this.drinkPrice.setText("" + customDrink.getPrice());
			concentrationValue.setText(String.valueOf(customDrink.getConcentration()));
			volumeValue.setText(String.valueOf(customDrink.getVolume()));
			this.drinkConcentration.setProgress((int) (customDrink.getConcentration() * 1000d));
			this.drinkVolume.setProgress((int) (customDrink.getVolume() * 100d));
		}

		this.drinkConcentration.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				int count;
				count = drinkConcentration.getProgress();
				concentrationValue.setText(String.valueOf(count / 1000d));
			}
		});

		this.drinkVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				int count;
				count = drinkVolume.getProgress();
				volumeValue.setText(String.valueOf(count / 100d));
			}
		});

		updateButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CustomDrinkDetailActivity.this.id != null) {
					if (customDrink != null) {
						
						CustomDrinkDetailActivity.this.customDrink.setName(CustomDrinkDetailActivity.this.name.getText() + "");
						CustomDrinkDetailActivity.this.customDrink.setNote(CustomDrinkDetailActivity.this.note.getText() + "");
						String priceString = CustomDrinkDetailActivity.this.drinkPrice.getText().toString().replaceAll(",", ".");
						double price = 0d;
						try {
							if (priceString != null && !"".equals(priceString))
								price = Double.parseDouble(priceString);
						} catch (Exception ex) {
							Log.d(TAG, "Bad price format", ex);
						}
						CustomDrinkDetailActivity.this.customDrink.setPrice(price);
						CustomDrinkDetailActivity.this.customDrink.setConcentration(CustomDrinkDetailActivity.this.drinkConcentration.getProgress() / 1000d);
						CustomDrinkDetailActivity.this.customDrink.setVolume(CustomDrinkDetailActivity.this.drinkVolume.getProgress() / 100d);
						String name = customDrink.getName();
						if (name == null || "".equals(name.trim())) {
							name = getResources().getText(R.string.drinkLabelGeneric).toString();
							customDrink.setName(name);
						}
						CustomDrinkDetailActivity.this.drinkDatabaseHelper.updateCustomDrink(CustomDrinkDetailActivity.this.id, customDrink);
						// Toast.makeText(CustomDrinkDetailActivity.this.getApplicationContext(),
						// getResources().getText(R.string.placeInfoUpdatedToast),
						// Toast.LENGTH_SHORT).show();
					} else {
						String name = (String) CustomDrinkDetailActivity.this.name.getText();
						String note = (String) CustomDrinkDetailActivity.this.note.getText();
						String priceString = CustomDrinkDetailActivity.this.drinkPrice.getText().toString().replaceAll(",", ".");
						double price = 0d;
						try {
							if (priceString != null && !"".equals(priceString))
								price = Double.parseDouble(priceString);
						} catch (Exception ex) {
							Log.d(TAG, "Bad price format", ex);
						}
						double concentration = CustomDrinkDetailActivity.this.drinkConcentration.getProgress() / 1000d;
						double volume = CustomDrinkDetailActivity.this.drinkVolume.getProgress() / 100d;
						
						if (name == null || "".equals(name.trim())) {
							name = getResources().getText(R.string.drinkLabelGeneric).toString();
							customDrink.setName(name);
						}
						CustomDrinkDetailActivity.this.drinkDatabaseHelper.updateCustomDrink(CustomDrinkDetailActivity.this.id, name, note, price, concentration, volume);
						// Toast.makeText(CustomDrinkDetailActivity.this.getApplicationContext(),
						// getResources().getText(R.string.placeInfoUpdatedToast),
						// Toast.LENGTH_SHORT).show();
					}
				}
			}
		});

		removeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CustomDrinkDetailActivity.this.id != null) {
					AlertDialog.Builder builder = new AlertDialog.Builder(CustomDrinkDetailActivity.this);
					builder.setMessage(getResources().getText(R.string.placeRemovePrompt)).setCancelable(true)
							.setPositiveButton(getResources().getText(R.string.yesAnswer), new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									if (customDrink != null) {
										CustomDrinkDetailActivity.this.drinkDatabaseHelper.removeCustomDrink(customDrink);
										// Toast.makeText(CustomDrinkDetailActivity.this.getApplicationContext(),
										// getResources().getText(R.string.placeRemoveToast),
										// Toast.LENGTH_SHORT).show();
										CustomDrinkDetailActivity.this.finish();
									} else {
										CustomDrinkDetailActivity.this.drinkDatabaseHelper.removeCustomDrink(CustomDrinkDetailActivity.this.id);
										// Toast.makeText(CustomDrinkDetailActivity.this.getApplicationContext(),
										// getResources().getText(R.string.placeRemoveToast),
										// Toast.LENGTH_SHORT).show();
										CustomDrinkDetailActivity.this.finish();
									}
								}
							}).setNegativeButton(getResources().getText(R.string.noAnswer), new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();

				}
			}
		});
		this.mapButton = (ImageButton) this.findViewById(R.id.map);
		mapButton.setVisibility(View.VISIBLE);
		this.mapButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Toast.makeText(getApplicationContext(),
				// getResources().getText(R.string.alreadyToast),
				// Toast.LENGTH_SHORT).show();

				Intent intent = new Intent(getApplicationContext(), DrinkMapsActivity.class);
				startActivity(intent);
			}
		});
		this.placesButton = (ImageButton) this.findViewById(R.id.places);
		placesButton.setVisibility(View.VISIBLE);
		this.placesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), DrinkPlacesActivity.class);
				startActivity(intent);
			}
		});

		this.settingsButton = (ImageButton) this.findViewById(R.id.settings);
		settingsButton.setVisibility(View.VISIBLE);
		this.settingsButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
				startActivity(intent);
			}
		});

		this.drinksButton = (ImageButton) this.findViewById(R.id.drinks);

		this.drinksButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), DrinkManagerListActivity.class);
				startActivity(intent);
				// Toast.makeText(getApplicationContext(),
				// getResources().getText(R.string.alreadyToast),
				// Toast.LENGTH_SHORT).show();

			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		BackgroundAdapter.updateBackgroundFromPrefs(prefs, this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = this.getMenuInflater();
		inflater.inflate(R.menu.optionmenu, menu);
		MenuItem settings = menu.findItem(R.id.settings);
		settings.setIntent(new Intent(this, SettingsActivity.class));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit:
			CustomDrinkDetailActivity.this.finish();
			return true;
		case R.id.settings:
			Intent settingsIntent = item.getIntent();
			this.startActivityForResult(settingsIntent, 0);
			return true;
		case android.R.id.home:
			// Toast.makeText(DrinkManagerListActivity.this.getApplicationContext(),
			// getResources().getText(R.string.alreadyToast),
			// Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(this, DrinkManagerListActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case R.id.drinks:
			Intent drinksIntent = new Intent(getApplicationContext(), DrinkManagerListActivity.class);
			this.startActivityForResult(drinksIntent, 0);
			return true;
		case R.id.places:
			Intent placesIntent = new Intent(getApplicationContext(), DrinkPlacesActivity.class);
			this.startActivityForResult(placesIntent, 0);
			return true;
		case R.id.custom:
			Intent customIntent = new Intent(this, CustomDrinksActivity.class);
			this.startActivityForResult(customIntent, 0);
			return true;
		case R.id.history:
			Intent historyIntent = new Intent(this, DrinkHistoryActivity.class);
			this.startActivityForResult(historyIntent, 0);
			// Toast.makeText(getApplicationContext(),
			// getResources().getText(R.string.alreadyToast),
			// Toast.LENGTH_SHORT).show();
			return true;
		case R.id.graphs:
			Intent graphsIntent = new Intent(this, DrinkGraphActivity.class);
			this.startActivityForResult(graphsIntent, 0);
			return true;
		case R.id.back:
			Intent backIntent = new Intent(getApplicationContext(), BackgroundChooserActivity.class);
			this.startActivityForResult(backIntent, 0);
			return true;
		case R.id.map:
			Intent mapsIntent = new Intent(getApplicationContext(), DrinkMapsActivity.class);
			this.startActivityForResult(mapsIntent, 0);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
